<template>
	<view class="reservoir-detail">
		<!-- 降雨研判卡片 -->
		<view class="info-card">
			<view class="card-header">
				<text class="card-title">降雨研判</text>
				<text class="analysis-period">{{ formatTimeRange() }}</text>
			</view>
			<view class="card-content">
				<view class="stats-grid">
					<view class="stat-item">
						<text class="stat-label">流域降雨量</text>
						<text class="stat-value">{{ calculateBasinRainfall() }}mm</text>
					</view>
					<view class="stat-item clickable" @click="scrollToStationRainfallTable">
						<text class="stat-label">测站总数</text>
						<text class="stat-value highlight">{{ getTotalStationCount() }}个</text>
					</view>
					<view class="stat-item clickable" @click="scrollToStationRainfallTable">
						<text class="stat-label">有雨测站</text>
						<text class="stat-value">{{ getRainyStationCount() }}个 ({{ getRainyStationPercentage() }}%)</text>
					</view>
					<view class="stat-item clickable" @click="scrollToStationRainfallTable">
						<text class="stat-label">暴雨测站</text>
						<text class="stat-value">{{ getStormStationCount() }}个 ({{ getStormStationPercentage() }}%)</text>
					</view>
					<view class="stat-item clickable" @click="scrollToStationRainfallTable">
						<text class="stat-label">大雨测站</text>
						<text class="stat-value">{{ getHeavyRainStationCount() }}个 ({{ getHeavyRainStationPercentage() }}%)</text>
					</view>
					<view class="stat-item clickable" @click="scrollToStationRainfallTable">
						<text class="stat-label">中雨测站</text>
						<text class="stat-value">{{ getModerateRainStationCount() }}个 ({{ getModerateRainStationPercentage() }}%)</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 时间选择器 -->
		<view class="simple-date-bar">
			<DateTimePicker 
				v-model="startDate" 
				:defaultDaysOffset="-1"
				@change="onStartDateChange"
			/>
			<text class="date-separator">至</text>
			<DateTimePicker 
				v-model="endDate" 
				:defaultDaysOffset="0"
				@change="onEndDateChange"
			/>
		</view>

		<!-- 泰森多边形可视化卡片 -->
		<view class="info-card">
			<view class="card-header">
				<view class="header-left">
					<text class="card-title">泰森多边形可视化</text>
					<view class="map-legend">
						<view class="legend-item">
							<view class="legend-color" style="background-color: #ff6600;"></view>
							<text class="legend-text">流域边界</text>
						</view>
						<view class="legend-item">
							<view class="legend-color" style="background-color: #0066cc;"></view>
							<text class="legend-text">泰森多边形</text>
						</view>
						<view class="legend-item">
							<view class="legend-color" style="background-color: #000000;"></view>
							<text class="legend-text">雨量站点</text>
						</view>
						<view class="legend-item">
							<view class="legend-color" style="background-color: #ff0000;"></view>
							<text class="legend-text">流域出口</text>
						</view>
					</view>
				</view>
				<view class="header-right" v-if="reservoirData.station_stcds && reservoirData.station_stcds.length > 0">
					<button 
						class="recalculate-btn" 
						@click="recalculateThiessen"
						:disabled="isRecalculating || loading"
					>
						{{ isRecalculating ? '计算中...' : '重新计算权重' }}
					</button>
				</view>
			</view>
			<view class="card-content">
				<!-- 地图区域 -->
				<view class="map-section">
					<!-- #ifdef H5 -->
					<LeafletMap 
						mapId="reservoir-leaflet-map"
						:center="[40.25, 122.7]"
						:zoom="8"
						@map-ready="onMapReady"
					/>
					<!-- 动态降雨量色带图例 -->
					<view class="dynamic-rainfall-legend" v-if="Object.keys(stationRainfallData).length > 0">
						<view class="legend-title">降雨量 (mm)</view>
						<view class="legend-colors">
							<view 
								v-for="(band, index) in calculateColorBandData()" 
								:key="index"
								class="legend-color-item"
							>
								<view 
									class="legend-color-block" 
									:style="{ backgroundColor: band.color }"
									></view>
								<text class="legend-color-label">{{ band.label }}</text>
							</view>
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<view class="map-not-supported">
						<text>当前环境不支持地图显示，请在浏览器中查看</text>
					</view>
					<!-- #endif -->
				</view>
			</view>
		</view>

		<!-- 测站降雨总量柱状图 -->
		<view class="info-card" v-show="getRainyStationCount() > 0">
			<view class="card-header">
				<text class="card-title">测站降雨总量</text>
			</view>
			<view class="card-content">
				<!-- 颜色图例 -->
				<view class="rainfall-legend">
					<view class="legend-item">
						<view class="legend-color" style="background-color: #90EE90;"></view>
						<text class="legend-text">0-5mm</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #32CD32;"></view>
						<text class="legend-text">5-15mm</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #1E90FF;"></view>
						<text class="legend-text">15-30mm</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #0000FF;"></view>
						<text class="legend-text">30mm以上</text>
					</view>
				</view>
				
				<view class="chart-container">
					<!-- #ifdef H5 -->
					<view class="chart-scroll-container">
						<canvas 
							id="rainfall-chart" 
							class="rainfall-chart"
							width="2400"
							height="400"
							:style="{ width: '2400px', height: '400px' }"
						></canvas>
					</view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<view class="chart-not-supported">
						<text>当前环境不支持图表显示，请在浏览器中查看</text>
					</view>
					<!-- #endif -->
				</view>
			</view>
		</view>

		<!-- 测站降雨量排序表格 -->
		<view class="info-card">
			<view class="card-header">
				<text class="card-title">测站降雨量排序</text>
			</view>
			<view class="card-content">
				<view class="station-rainfall-table">
					<view class="table-header-row">
						<text class="table-header-cell station-name">测站名称</text>
						<text class="table-header-cell rainfall-value">降雨(mm)</text>
						<text class="table-header-cell station-address">站址</text>
					</view>
					<view 
						v-for="(station, index) in getSortedStationRainfall()" 
						:key="station.stationCode"
						class="table-row clickable-row"
						:class="{ 'even-row': index % 2 === 0 }"
						@click="navigateToStationDetail(station)"
					>
						<text class="table-cell station-name">{{ station.stationName }}</text>
						<text class="table-cell rainfall-value" :style="{ color: getChartBarColor(station.rainfall) }">
							{{ station.rainfall.toFixed(1) }}
						</text>
						<text class="table-cell station-address">{{ station.stationAddress }}</text>
					</view>
					<view v-if="getSortedStationRainfall().length === 0" class="empty-table">
						<text class="empty-text">暂无降雨数据</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { API_BASE_URL } from '@/config/api.js'
import DateTimePicker from './DateTimePicker.vue'
import LeafletMap from '@/components/LeafletMap.vue'
// #ifdef H5
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
// #endif

// 定义props
const props = defineProps({
	basinCode: {
		type: String,
		required: true
	}
})

// 定义emits
const emit = defineEmits(['refresh'])

// 响应式数据
const reservoirData = ref({})
const thiessenData = ref(null)
const loading = ref(false)
const isRecalculating = ref(false)

const startDate = ref({ year: '', month: '', day: '', hour: '' })
const endDate = ref({ year: '', month: '', day: '', hour: '' })

// 获取所有测站的降雨数据统计
const rainfallSummaryData = ref(null)

// 泰森多边形着色相关数据
const stationRainfallData = ref({}) // 存储每个测站的降雨量数据
const maxRainfall = ref(0) // 最大降雨量，用于颜色计算

// 地图相关变量
let map = null
let basinLayer = null
let polygonLayer = null
let stationLayer = null
let outletLayer = null

// 地图数据
const basinGeometry = ref(null)
const polygonData = ref(null)
const stationData = ref([])
const outletPoint = ref(null)

// 获取流域详情
const fetchReservoirDetail = async (basinCode) => {
	try {
		console.log('正在调用水库详情API:', `/api/get_reservoir_by_stcd?basin=${basinCode}`)
		const response = await uni.request({
			url: `${API_BASE_URL}/api/get_reservoir_by_stcd?basin=${basinCode}`,
			method: 'GET'
		})
		
		console.log('水库详情API响应:', response)
		if (response.data.success) {
			reservoirData.value = response.data.data
			
			// 设置地图相关数据
			basinGeometry.value = response.data.data.geometry_geojson
			outletPoint.value = {
				lon: response.data.data.outlet_coordinates.longitude,
				lat: response.data.data.outlet_coordinates.latitude,
				name: response.data.data.stnm
			}
			
			// 获取详情后自动获取泰森多边形数据
			await fetchThiessenData(basinCode)
		}
	} catch (error) {
		console.error('获取水库详情失败:', error)
	}
}

// 获取泰森多边形数据
const fetchThiessenData = async (basinCode) => {
	try {
		loading.value = true
		console.log('正在调用泰森多边形API:', `/api/get_thiessen_analysis?basin_code=${basinCode}`)
		const response = await uni.request({
			url: `${API_BASE_URL}/api/get_thiessen_analysis?basin_code=${basinCode}`,
			method: 'GET'
		})
		
		console.log('泰森多边形API响应:', response)
		if (response.data.success) {
			thiessenData.value = response.data.data
			
			// 处理地图相关数据
			polygonData.value = response.data.data?.polygons || { type: 'FeatureCollection', features: [] }
			const features = polygonData.value?.features || []
			
			if (features.length > 0) {
				stationData.value = features.map(feature => ({
					stationCode: feature.properties?.stcd,
					stationName: feature.properties?.name,
					lon: feature.properties?.lon != null ? parseFloat(feature.properties.lon) : null,
					lat: feature.properties?.lat != null ? parseFloat(feature.properties.lat) : null,
					sttype: feature.properties?.sttype,
					area: feature.properties?.area ?? 0,
					weight: feature.properties?.weight ?? 0,
					geometry: feature.geometry || null
				}))
			} else if (Array.isArray(response.data.data?.stations) && response.data.data.stations.length > 0) {
				stationData.value = response.data.data.stations.map(st => ({
					stationCode: st.stcd,
					stationName: st.name,
					lon: st.lon != null ? parseFloat(st.lon) : null,
					lat: st.lat != null ? parseFloat(st.lat) : null,
					sttype: st.sttype,
					area: st.area ?? 0,
					weight: st.weight ?? 0,
					geometry: null
				}))
			} else {
				stationData.value = []
			}
			
			// 等待loading状态更新
			loading.value = false
			
			// 等待DOM更新
			await nextTick()
			
			// 等待地图初始化完成后再添加图层
			await waitForMapInitialization()
			
			// 快速添加图层（不包含降雨数据着色）
			if (map) {
				addBasinLayer()
				addPolygonLayer() // 这里会异步加载降雨数据并更新颜色
				addOutletLayer()
				addStationLayer()
			}
		}
	} catch (error) {
		console.error('获取泰森多边形数据失败:', error)
		loading.value = false
	}
}

// 刷新按钮处理
const handleRefresh = () => {
	if (props.basinCode) {
		fetchThiessenData(props.basinCode)
	}
	emit('refresh')
}

// 重新计算泰森多边形权重并刷新
const recalculateThiessen = async () => {
	if (!props.basinCode) {
		console.warn('没有流域编码，无法重新计算')
		return
	}
	
	if (!reservoirData.value.station_stcds || reservoirData.value.station_stcds.length === 0) {
		console.warn('该流域没有关联测站，无法重新计算')
		return
	}
	
	try {
		isRecalculating.value = true
		
		// 使用流域关联的测站编码
		const stationCodes = reservoirData.value.station_stcds.map(stcd => String(stcd)).filter(Boolean)
		console.log('触发重新计算:', { basin_code: props.basinCode, body: stationCodes })
		
		// 调用重新计算API
		const response = await uni.request({
			url: `${API_BASE_URL}/api/calculate_thiessen_analysis?basin_code=${props.basinCode}`,
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			},
			data: stationCodes
		})
		
		console.log('重新计算API响应:', response)
		
		if (response.data && (response.data.success === true || response.data.code === 200)) {
			console.log('泰森多边形权重计算成功，正在刷新数据')
			// 重新获取泰森多边形数据
			await fetchThiessenData(props.basinCode)
		} else {
			console.error('重新计算失败响应:', response.data)
		}
	} catch (error) {
		console.error('重新计算请求失败:', error)
	} finally {
		isRecalculating.value = false
	}
}

// 等待地图初始化完成
const waitForMapInitialization = async () => {
	// 最多等待5秒
	const maxWaitTime = 5000
	const checkInterval = 100
	let waitedTime = 0
	
	while (!map && waitedTime < maxWaitTime) {
		await new Promise(resolve => setTimeout(resolve, checkInterval))
		waitedTime += checkInterval
	}
	
	if (!map) {
		console.warn('地图初始化超时，可能存在问题')
	} else {
		console.log('地图初始化完成，可以添加图层')
	}
}

// 由组件回调提供地图实例
const onMapReady = (m) => {
	map = m
	// 地图就绪后添加各图层（如有数据）
	addBasinLayer()
	addPolygonLayer()
	addOutletLayer()
	addStationLayer()
}

// 添加流域边界图层
const addBasinLayer = () => {
	// #ifdef H5
	if (!map || !basinGeometry.value) return
	
	// 清除已有的流域边界图层
	if (basinLayer) {
		map.removeLayer(basinLayer)
		basinLayer = null
	}
	
	console.log('添加流域边界')
	basinLayer = L.geoJSON(basinGeometry.value, {
		style: {
			color: '#ff6600',
			weight: 3,
			fillOpacity: 0,
			opacity: 1
		}
	}).addTo(map)
	
	// 调整地图视野到流域边界
	map.fitBounds(basinLayer.getBounds())
	// #endif
}

// 添加泰森多边形图层（不包含着色，先快速显示）
const addPolygonLayer = () => {
	// #ifdef H5
	if (!map || !polygonData.value) return
	
	// 清除已有的泰森多边形图层
	if (polygonLayer) {
		map.removeLayer(polygonLayer)
		polygonLayer = null
	}
	
	console.log('添加泰森多边形')
	polygonLayer = L.geoJSON(polygonData.value, {
		style: () => {
			// 初始使用默认颜色，快速显示
			return {
				color: '#0066cc',
				weight: 1,
				fillOpacity: 0.6,
				fillColor: '#e8f4fd', // 默认浅蓝色
			}
		},
		onEachFeature: (feature, layer) => {
			// 初始弹窗，不包含降雨量信息
			const stationCode = feature.properties?.stcd
			const stationName = feature.properties?.name
			
			layer.bindPopup(`
				<strong>${stationName}</strong><br>
				站点代码: ${stationCode}<br>
				正在加载降雨数据...
			`)
		}
	}).addTo(map)
	
	// 异步获取降雨数据并更新颜色
	setTimeout(async () => {
		try {
			await fetchAllStationRainfallData()
			updatePolygonColors()
		} catch (error) {
			console.error('异步加载降雨数据失败:', error)
		}
	}, 100)
	// #endif
}

// 添加测站标记图层
const addStationLayer = () => {
	// #ifdef H5
	if (!map || !stationData.value.length) return
	
	// 清除已有的测站图层
	if (stationLayer) {
		map.removeLayer(stationLayer)
		stationLayer = null
	}
	
	const markers = []
	
	stationData.value.forEach(station => {
		let lat, lng
		
		if (station.lat && station.lon) {
			// 如果数据中有经纬度坐标，直接使用
			lat = station.lat
			lng = station.lon
		} else if (station.geometry) {
			// 计算多边形中心点
			const bounds = L.geoJSON(station.geometry).getBounds()
			lat = bounds.getCenter().lat
			lng = bounds.getCenter().lng
		} else {
			return // 没有坐标信息，跳过
		}
		
		// 根据sttype设置不同颜色
		let markerColor = '#000000' // 默认黑色
		switch (station.sttype) {
			case 'PP':
				markerColor = '#000000' // 黑色
				break
			case 'RR':
				markerColor = '#0066cc' // 蓝色
				break
			case 'ZZ':
			case 'ZQ':
				markerColor = '#00cc66' // 绿色
				break
			default:
				markerColor = '#000000' // 黑色
		}
		
		// 创建圆点标记
		const circleMarker = L.circleMarker([lat, lng], {
			radius: 4,
			fillColor: markerColor,
			color: markerColor,
			weight: 1,
			opacity: 1,
			fillOpacity: 1
		})
		
		// 为圆点添加弹窗
		circleMarker.bindPopup(`
			<strong>${station.stationName}</strong><br>
			站点代码: ${station.stationCode}<br>
			权重: ${station.weight.toFixed(4)}
		`)
		
		markers.push(circleMarker)
	})
	
	if (markers.length > 0) {
		stationLayer = L.layerGroup(markers).addTo(map)
	}
	// #endif
}

// 添加出口点图层
const addOutletLayer = () => {
	// #ifdef H5
	if (!map || !outletPoint.value) return
	
	// 清除已有的出口点图层
	if (outletLayer) {
		map.removeLayer(outletLayer)
		outletLayer = null
	}
	
	const { lon, lat, name } = outletPoint.value
	
	// 创建红色圆点标记
	const outletMarker = L.circleMarker([lat, lon], {
		radius: 8,
		fillColor: '#ff0000',
		color: '#ff0000',
		weight: 2,
		opacity: 1,
		fillOpacity: 0.8
	})
	
	// 为出口点添加弹窗
	outletMarker.bindPopup(`
		<strong>流域出口</strong><br>
		名称: ${name}<br>
		坐标: ${lon}°, ${lat}°
	`)
	
	outletLayer = L.layerGroup([outletMarker]).addTo(map)
	// #endif
}

// 组件挂载时地图由子组件自动初始化并在 map-ready 中回传实例
onMounted(async () => {
	// 保留占位，其他初始化逻辑不变
	await nextTick()
})

// 监听basinCode变化
watch(() => props.basinCode, (newCode) => {
	if (newCode) {
		fetchReservoirDetail(newCode)
	}
}, { immediate: true })

// 时间选择器事件处理
const onStartDateChange = (value) => {
	console.log('降雨时间变更:', startDate.value, endDate.value)
	handleQueryButtonClick()
}

const onEndDateChange = (value) => {
	console.log('降雨时间变更:', startDate.value, endDate.value)
	handleQueryButtonClick()
}

// 滚动跳转函数
const scrollToStationRainfallTable = () => {
	// #ifdef H5
	// 在H5环境中，使用DOM方法
	const tables = document.querySelectorAll('.station-rainfall-table')
	if (tables.length > 0) {
		// 找到表格的父级info-card容器
		const infoCard = tables[0].closest('.info-card')
		if (infoCard) {
			infoCard.scrollIntoView({
				behavior: 'smooth',
				block: 'start'
			})
		}
	}
	// #endif
	
	// #ifndef H5
	// 在非H5环境中，使用uni-app的API
	uni.pageScrollTo({
		selector: '.station-rainfall-table',
		duration: 300
	})
	// #endif
}

// 格式化日期时间对象为字符串
const formatDateTime = (dateObj) => {
	return `${dateObj.year}-${dateObj.month}-${dateObj.day} ${dateObj.hour}:00:00`
}

// 数据验证函数（统一的验证逻辑）
const validateRainfallData = (record) => {
	if (!record || typeof record !== 'object') return false
	
	// 检查必需字段
	const requiredFields = ['stcd']
	const hasRequiredFields = requiredFields.every(field => 
		record.hasOwnProperty(field) && record[field] !== null && record[field] !== undefined
	)
	
	if (!hasRequiredFields) return false
	
	// 检查是否有有效的降雨数据
	const rainfallFields = ['precipitation']
	const hasValidRainfall = rainfallFields.some(field => {
		const value = parseFloat(record[field])
		return !isNaN(value) && value >= 0 && value <= 500
	})
	
	return hasValidRainfall
}

// 格式化降雨数据 - 保留所有有效数据包括0值
const formatRainfallRecord = (record, dateTimeKey) => {
	const precipitation = parseFloat(record.precipitation)
	return {
		time: dateTimeKey,
		value: Math.round(precipitation * 10) / 10, // 保留1位小数
		unit: 'mm',
		stationName: record.station_name || '未知站点',
		stationCode: record.stcd,
		rainfallLevel: getRainfallLevel(precipitation)
	}
}

// 获取降雨等级
const getRainfallLevel = (precipitation) => {
	const levels = [
		{ min: 0, max: 0, level: '无降水' },
		{ min: 0, max: 5, level: '小雨' },
		{ min: 5, max: 15, level: '中雨' },
		{ min: 15, max: 30, level: '大雨' },
		{ min: 30, max: 70, level: '暴雨' },
		{ min: 70, max: Infinity, level: '大暴雨' }
	]
	
	if (precipitation === 0) return levels[0].level
	return levels.find(level => precipitation > level.min && precipitation < level.max)?.level || levels[levels.length - 1].level
}

// 处理查询按钮点击事件
// 跳转到测站详情页面
const navigateToStationDetail = (station) => {
	console.log('跳转到测站详情页面:', station)
	
	// 格式化时间参数
	const startTimeParam = formatDateTime(startDate.value)
	const endTimeParam = formatDateTime(endDate.value)
	
	console.log('传递时间参数:', {
		startTime: startTimeParam,
		endTime: endTimeParam
	})
	
	// 使用uni.navigateTo进行页面跳转，保持当前页面不刷新
	uni.navigateTo({
		url: `/pages/station/station-detail?stationCode=${encodeURIComponent(station.stationCode)}&stationName=${encodeURIComponent(station.stationName)}&basinCode=${encodeURIComponent(props.basinCode)}&startTime=${encodeURIComponent(startTimeParam)}&endTime=${encodeURIComponent(endTimeParam)}`,
		success: () => {
			console.log('跳转成功')
		},
		fail: (error) => {
			console.error('跳转失败:', error)
			// 如果页面路由不存在，尝试使用组件方式
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			})
		}
	})
}

// 更新泰森多边形颜色（异步着色函数）
const updatePolygonColors = () => {
	if (polygonLayer && map) {
		// 遍历图层中的每个要素，直接更新样式
		polygonLayer.eachLayer((layer) => {
			const feature = layer.feature
			if (feature && feature.properties) {
				const stationCode = feature.properties.stcd
				const stationName = feature.properties.name
				const rainfall = stationRainfallData.value[stationCode] || 0
				const fillColor = getRainfallColor(rainfall, maxRainfall.value)
				
				// 直接设置新的样式，无需重新创建图层
				layer.setStyle({
					color: '#0066cc',
					weight: 1,
					fillOpacity: 0.6,
					fillColor: fillColor,
				})
				
				// 更新弹窗内容
				layer.bindPopup(`
					<strong>${stationName}</strong><br>
					站点代码: ${stationCode}<br>
					时间段降雨量: ${rainfall.toFixed(2)} mm
				`)
			}
		})
	}
}

const handleQueryButtonClick = async () => {
	if (!stationData.value || stationData.value.length === 0) {
		console.warn('没有测站数据，无法进行降雨面着色')
		return
	}
	
	try {
		console.log('开始重新获取所有测站降雨数据并更新着色')
		
		// 重新获取所有测站的降雨数据
		await fetchAllStationRainfallData()
		
		// 更新泰森多边形的颜色
		updatePolygonColors()
		
		console.log('降雨面着色更新完成')
	} catch (error) {
		console.error('更新降雨面着色失败:', error)
	}
}

// 获取测站一周内降雨数据总和
// 根据降雨量计算颜色
const getRainfallColor = (rainfall, maxRainfall) => {
	if (maxRainfall === 0) return 'rgb(255, 245, 230)' // 默认浅橙色
	if (rainfall === 0) return 'rgb(255, 245, 230)' // 浅橙色 - 无降雨
	
	// 计算降雨量比例 (0-1)
	const ratio = Math.min(rainfall / maxRainfall, 1)
	
	// 根据最大降雨量确定色带数量（与calculateColorBandData保持一致）
	let bandCount = 4 // 默认4个色带
	if (maxRainfall <= 5) {
		bandCount = 2
	} else if (maxRainfall <= 15) {
		bandCount = 3
	} else if (maxRainfall <= 30) {
		bandCount = 4
	} else {
		bandCount = 5
	}
	
	// 定义固定的颜色序列，每个色带一个固定颜色 - 增强对比度的橙色到红色渐变
	const colors = [
		{ r: 255, g: 220, b: 130 },  // 浅橙色 - 第1级
		{ r: 255, g: 180, b: 100 },  // 橙色 - 第2级
		{ r: 255, g: 130, b: 50 },   // 深橙色 - 第3级
		{ r: 255, g: 80, b: 20 },    // 橙红色 - 第4级
		{ r: 200, g: 40, b: 10 }     // 深红色 - 第5级
	]
	
	// 根据比例确定当前值应该在哪个色带区间
	// 修复边界值问题：确保与calculateColorBandData的区间判断逻辑一致
	let bandIndex = 0
	for (let i = 1; i <= bandCount; i++) {
		const upperBound = maxRainfall * (i / bandCount)
		const lowerBound = i === 1 ? 0 : maxRainfall * ((i - 1) / bandCount)
		
		// 使用与calculateColorBandData相同的区间判断逻辑
		if (rainfall > lowerBound && rainfall <= upperBound) {
			bandIndex = i - 1
			break
		}
	}
	
	// 确保索引在有效范围内
	if (bandIndex >= bandCount) bandIndex = bandCount - 1
	
	// 关键修复：同一色带等级使用固定颜色，不进行插值
	// 这样确保同一色带等级的所有降雨量都显示相同的颜色
	const color = colors[bandIndex]
	
	return `rgb(${color.r}, ${color.g}, ${color.b})`
}

// 为柱状图和表格提供颜色计算函数（4个分组）
const getChartBarColor = (rainfall) => {
	if (rainfall >= 30) {
		return '#0000FF' // 蓝色 - 30mm以上
	} else if (rainfall > 15) {
		return '#1E90FF' // 道奇蓝 - 15-30mm
	} else if (rainfall > 5) {
		return '#32CD32' // 酸橙绿 - 5-15mm
	} else if (rainfall > 0) {
		return '#90EE90' // 浅绿色 - 0-5mm
	} else {
		return '#E0E0E0' // 灰色 - 无降雨
	}
}

// 计算动态色带数据（离散区间样式 - 与渐变着色一致）
const calculateColorBandData = () => {
	const allRainfallValues = Object.values(stationRainfallData.value)
	const rainfallValues = allRainfallValues.filter(val => val > 0)
	const maxVal = maxRainfall.value
	
	if (maxVal === 0 || allRainfallValues.length === 0) {
		return [{ value: 0, color: getRainfallColor(0, 0), label: '0' }]
	}
	
	// 检查是否有0值数据
	const hasZeroValues = allRainfallValues.some(val => val === 0)
	
	// 生成离散区间样式的色带数据
	const colorBands = []
	
	// 如果有0值数据，单独添加0值色带
	if (hasZeroValues) {
		colorBands.push({
			value: 0,
			color: getRainfallColor(0, maxVal),
			label: '0'
		})
	}
	
	// 根据最大降雨量动态生成色带区间数量
	let bandCount = 4 // 默认4个色带
	if (maxVal <= 5) {
		bandCount = 2
	} else if (maxVal <= 15) {
		bandCount = 3
	} else if (maxVal <= 30) {
		bandCount = 4
	} else {
		bandCount = 5
	}
	
	// 生成离散区间
	for (let i = 1; i <= bandCount; i++) {
		const ratio = i / bandCount
		const upperBound = maxVal * ratio
		let lowerBound
		
		// 确定下界
		if (i === 1) {
			lowerBound = hasZeroValues ? 0 : 0  // 如果有0值数据，第一个区间从0.1开始
		} else {
			lowerBound = maxVal * (i - 1) / bandCount
		}
		
		// 生成区间标签 - 离散样式
		let label
		if (i === 1 && !hasZeroValues) {
			// 第一个区间且没有0值时，显示为 "0-xx"
			label = `0-${upperBound.toFixed(upperBound < 10 ? 1 : 0)}`
		} else if (i === 1 && hasZeroValues) {
			// 第一个区间且有0值时，显示为 "0.1-xx"
			label = `${lowerBound}-${upperBound.toFixed(upperBound < 10 ? 1 : 0)}`
		} else {
			// 其他区间显示为 "xx-yy"
			label = `${lowerBound.toFixed(lowerBound < 10 ? 1 : 0)}-${upperBound.toFixed(upperBound < 10 ? 1 : 0)}`
		}
		
		// 关键修复：根据实际降雨数据计算该区间的代表性颜色
		// 找出落在当前区间内的所有实际降雨值
		const valuesInRange = allRainfallValues.filter(val => 
			val > lowerBound && val <= upperBound
		)
		
		let colorValue
		if (valuesInRange.length > 0) {
			// 如果有实际数据落在这个区间，使用这些数据的平均值
			colorValue = valuesInRange.reduce((sum, val) => sum + val, 0) / valuesInRange.length
		} else {
			// 如果没有实际数据落在这个区间，使用区间中点
			colorValue = (lowerBound + upperBound) / 2
		}
		
		colorBands.push({
			value: colorValue,
			color: getRainfallColor(colorValue, maxVal),
			label: label
		})
	}
	
	return colorBands
}

const fetchAllStationRainfallData = async () => {
	try {
		console.log('开始获取所有测站的降雨汇总数据')
		
		// 提取所有测站编码
		const stationIds = stationData.value
			.map(station => station.stationCode)
			.filter(code => code) // 过滤掉空值
		
		if (stationIds.length === 0) {
			console.warn('没有有效的测站编码')
			rainfallSummaryData.value = null
			return
		}
		
		const startTime = formatDateTime(startDate.value)
		const endTime = formatDateTime(endDate.value)
		
		console.log('调用降雨汇总API:', { stationIds, startTime, endTime })
		
		const response = await uni.request({
			url: `${API_BASE_URL}/api/get_stations_rainfall_summary`,
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			},
			data: {
				station_ids: stationIds,
				start_time_str: startTime,
				end_time_str: endTime
			}
		})
		
		if (response.data.success) {
			rainfallSummaryData.value = response.data.data
			
			// 更新原有的数据结构以保持兼容性
			const rainfallData = {}
			let max = 0
			
			response.data.data.station_list.forEach(station => {
				rainfallData[station.station_code] = station.total_rainfall
				if (station.total_rainfall > max) {
					max = station.total_rainfall
				}
			})
			
			stationRainfallData.value = rainfallData
			maxRainfall.value = max
			
			console.log('降雨汇总数据获取完成:', response.data.data)
		} else {
			console.error('获取降雨汇总数据失败:', response.data)
		}
	} catch (error) {
		console.error('获取测站降雨数据失败:', error)
	}
}

// 统计信息计算函数 - 使用API返回的数据
// 格式化时间范围
const formatTimeRange = () => {
	if (!startDate.value || !endDate.value) return ''
	return `${startDate.value.year}-${startDate.value.month}-${startDate.value.day} ${startDate.value.hour}时 至 ${endDate.value.year}-${endDate.value.month}-${endDate.value.day} ${endDate.value.hour}时`
}

// 计算流域降雨量 - 使用API返回的总降雨量/平均降雨量
const calculateBasinRainfall = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.summary) {
		return '0.0'
	}
	return rainfallSummaryData.value.summary.average_rainfall.toFixed(1)
}

// 获取测站总数 - 使用API返回的数据
const getTotalStationCount = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.summary) {
		return stationData.value.length
	}
	return rainfallSummaryData.value.summary.total_stations
}

// 获取有雨测站数量 - 使用API返回的数据
const getRainyStationCount = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.summary) {
		return 0
	}
	return rainfallSummaryData.value.summary.stations_with_rain
}

// 获取有雨测站百分比 - 使用API返回的数据
const getRainyStationPercentage = () => {
	const total = getTotalStationCount()
	if (total === 0) return '0'
	const rainy = getRainyStationCount()
	return ((rainy / total) * 100).toFixed(0)
}

// 获取中雨测站数量 - 使用API返回的数据
const getModerateRainStationCount = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.rainfall_stats) {
		return 0
	}
	return rainfallSummaryData.value.rainfall_stats.moderate_rain.count
}

// 获取中雨测站百分比 - 使用API返回的数据
const getModerateRainStationPercentage = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.rainfall_stats) {
		return '0'
	}
	return rainfallSummaryData.value.rainfall_stats.moderate_rain.percentage.toFixed(0)
}

// 获取大雨测站数量 - 使用API返回的数据
const getHeavyRainStationCount = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.rainfall_stats) {
		return 0
	}
	return rainfallSummaryData.value.rainfall_stats.heavy_rain.count
}

// 获取大雨测站百分比 - 使用API返回的数据
const getHeavyRainStationPercentage = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.rainfall_stats) {
		return '0'
	}
	return rainfallSummaryData.value.rainfall_stats.heavy_rain.percentage.toFixed(0)
}

// 获取暴雨测站数量 - 使用API返回的数据
const getStormStationCount = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.rainfall_stats) {
		return 0
	}
	return rainfallSummaryData.value.rainfall_stats.storm_rain.count
}

// 获取暴雨测站百分比 - 使用API返回的数据
const getStormStationPercentage = () => {
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.rainfall_stats) {
		return '0'
	}
	return rainfallSummaryData.value.rainfall_stats.storm_rain.percentage.toFixed(0)
}

// 获取按降雨量排序的测站数据
const getSortedStationRainfall = () => {
	console.log('getSortedStationRainfall 被调用')
	console.log('rainfallSummaryData.value:', rainfallSummaryData.value)
	
	if (!rainfallSummaryData.value || !rainfallSummaryData.value.station_list) {
		console.log('没有降雨汇总数据或测站列表为空')
		return []
	}
	
	console.log('station_list:', rainfallSummaryData.value.station_list)
	
	// 将测站数据转换为数组并按降雨量排序
	const stationArray = rainfallSummaryData.value.station_list.map(station => ({
		stationCode: station.station_code,
		stationName: station.station_name || station.station_code,
		rainfall: station.total_rainfall || 0,
		stationAddress: station.station_address
	}))
	
	console.log('转换后的测站数组:', stationArray)
	
	// 按降雨量从大到小排序
	const sortedArray = stationArray.sort((a, b) => b.rainfall - a.rainfall)
	console.log('排序后的测站数组:', sortedArray)
	
	return sortedArray
}

// 初始化柱状图
const initRainfallChart = () => {
	// #ifdef H5
	nextTick(() => {
		console.log('initRainfallChart: 开始初始化柱状图')
		
		// 尝试多种方式获取canvas元素
		let canvas = null
		let ctx = null
		
		// 方法1: 直接通过ID获取
		canvas = document.getElementById('rainfall-chart')
		console.log('initRainfallChart: 方法1获取Canvas元素:', canvas)
		
		if (canvas && typeof canvas.getContext === 'function') {
			try {
				ctx = canvas.getContext('2d')
				console.log('initRainfallChart: 方法1成功获取上下文')
			} catch (error) {
				console.log('initRainfallChart: 方法1获取上下文失败:', error)
			}
		}
		
		// 方法2: 如果方法1失败，尝试查找内部的canvas元素
		if (!ctx && canvas) {
			const innerCanvas = canvas.querySelector('canvas')
			console.log('initRainfallChart: 方法2查找内部canvas:', innerCanvas)
			if (innerCanvas && typeof innerCanvas.getContext === 'function') {
				try {
					ctx = innerCanvas.getContext('2d')
					canvas = innerCanvas // 更新canvas引用
					console.log('initRainfallChart: 方法2成功获取上下文')
				} catch (error) {
					console.log('initRainfallChart: 方法2获取上下文失败:', error)
				}
			}
		}
		
		// 方法3: 直接查询所有canvas元素
		if (!ctx) {
			const allCanvas = document.querySelectorAll('canvas')
			console.log('initRainfallChart: 方法3找到所有canvas元素:', allCanvas.length)
			for (let i = 0; i < allCanvas.length; i++) {
				const canvasEl = allCanvas[i]
				if (canvasEl.id === 'rainfall-chart' || canvasEl.className.includes('rainfall-chart')) {
					try {
						ctx = canvasEl.getContext('2d')
						canvas = canvasEl
						console.log('initRainfallChart: 方法3成功获取上下文')
						break
					} catch (error) {
						console.log('initRainfallChart: 方法3获取上下文失败:', error)
					}
				}
			}
		}
		
		if (!canvas || !ctx) {
			console.error('initRainfallChart: 无法获取有效的canvas元素和上下文')
			return
		}
		
		const sortedData = getSortedStationRainfall()
		console.log('initRainfallChart: 柱状图数据:', sortedData)
		console.log('initRainfallChart: 数据条数:', sortedData.length)
		
		if (sortedData.length === 0) {
			// 显示无数据提示
			ctx.fillStyle = '#666'
			ctx.font = '20px Arial'
			ctx.textAlign = 'center'
			ctx.fillText('暂无降雨数据', 1200, 200)
			return
		}
		
		// 清空画布 - 使用更宽的尺寸以支持横向滚动
		ctx.clearRect(0, 0, 2400, 400)
		
		// 设置画布尺寸 - 增加宽度以容纳更多测站，支持横向滚动
		const chartWidth = 2400
		const chartHeight = 400
		const padding = { top: 30, right: 40, bottom: 80, left: 60 }
		const plotWidth = chartWidth - padding.left - padding.right
		const plotHeight = chartHeight - padding.top - padding.bottom
		
		// 计算最大值
		const maxValue = Math.max(...sortedData.map(d => d.rainfall))
		const yScale = plotHeight / (maxValue * 1.1) // 留10%的空间
		
		// 绘制背景
		ctx.fillStyle = '#ffffff'
		ctx.fillRect(0, 0, chartWidth, chartHeight)
		
		// 绘制网格线
		ctx.strokeStyle = '#f0f0f0'
		ctx.lineWidth = 1
		
		// 水平网格线
		const ySteps = 6
		for (let i = 0; i <= ySteps; i++) {
			const y = padding.top + (plotHeight / ySteps) * i
			ctx.beginPath()
			ctx.moveTo(padding.left, y)
			ctx.lineTo(padding.left + plotWidth, y)
			ctx.stroke()
		}
		
		// 绘制坐标轴
		ctx.strokeStyle = '#ddd'
		ctx.lineWidth = 1
		
		// Y轴
		ctx.beginPath()
		ctx.moveTo(padding.left, padding.top)
		ctx.lineTo(padding.left, padding.top + plotHeight)
		ctx.stroke()
		
		// X轴
		ctx.beginPath()
		ctx.moveTo(padding.left, padding.top + plotHeight)
		ctx.lineTo(padding.left + plotWidth, padding.top + plotHeight)
		ctx.stroke()

		// 计算柱子宽度和间距 - 确保均匀分布
		const totalBars = sortedData.length
		const availableWidth = plotWidth
		const barWidth = Math.max(20, availableWidth / totalBars * 0.7) // 最小宽度20px，占70%空间
		const barSpacing = availableWidth / totalBars * 0.3 // 间距占30%空间
		
		// 绘制柱状图
		sortedData.forEach((station, index) => {
			const x = padding.left + index * (barWidth + barSpacing) + barSpacing / 2
			const barHeight = station.rainfall * yScale
			const y = padding.top + plotHeight - barHeight
			
			// 绘制柱子阴影
			ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
			ctx.fillRect(x + 1, y + 1, barWidth, barHeight)
			
			// 绘制柱子
			ctx.fillStyle = getChartBarColor(station.rainfall)
			ctx.fillRect(x, y, barWidth, barHeight)
			
			// 绘制柱子边框
			ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)'
			ctx.lineWidth = 1
			ctx.strokeRect(x, y, barWidth, barHeight)
			
			// 绘制数值标签
			if (station.rainfall > 0) {
				ctx.fillStyle = '#333'
				ctx.font = 'bold 12px Arial'
				ctx.textAlign = 'center'
				ctx.fillText(station.rainfall.toFixed(1), x + barWidth / 2, y - 5)
			}
			
			// 绘制测站名称（垂直显示）
			ctx.save()
			ctx.translate(x + barWidth / 2, padding.top + plotHeight + 15)
			ctx.rotate(-Math.PI / 2)
			ctx.textAlign = 'left'
			ctx.font = '11px Arial'
			ctx.fillStyle = '#555'
			
			// 限制测站名称长度
			let displayName = station.stationName
			if (displayName.length > 6) {
				displayName = displayName.substring(0, 4) + '..'
			}
			ctx.fillText(displayName, 0, 0)
			ctx.restore()
		})
		
		// 绘制Y轴标签
		ctx.fillStyle = '#666'
		ctx.font = '12px Arial'
		ctx.textAlign = 'right'
		for (let i = 0; i <= ySteps; i++) {
			const value = (maxValue * 1.1 / ySteps) * i
			const y = padding.top + plotHeight - (value * yScale)
			ctx.fillText(value.toFixed(0), padding.left - 10, y + 4)
		}
		
		// Y轴标题
		ctx.save()
		ctx.translate(20, padding.top + plotHeight / 2)
		ctx.rotate(-Math.PI / 2)
		ctx.textAlign = 'center'
		ctx.font = 'bold 14px Arial'
		ctx.fillStyle = '#333'
		ctx.fillText('降雨量 (mm)', 0, 0)
		ctx.restore()
	})
	// #endif
}

// 监听降雨数据变化，更新图表
watch(rainfallSummaryData, () => {
	nextTick(() => {
		// 延迟初始化，确保DOM完全渲染
		setTimeout(() => {
			initRainfallChart()
		}, 200)
	})
}, { deep: true })

// 监听测站数据变化，自动获取降雨数据
watch(stationData, async (newStationData) => {
	if (newStationData && newStationData.length > 0) {
		// 当测站数据加载完成后，立即获取降雨汇总数据
		try {
			await fetchAllStationRainfallData()
			console.log('测站数据加载完成，降雨数据已获取')
		} catch (error) {
			console.error('自动获取降雨数据失败:', error)
		}
	}
}, { deep: true })

// 监听时间变化，自动更新降雨数据
watch([startDate, endDate], async () => {
	if (stationData.value && stationData.value.length > 0) {
		try {
			console.log('时间变化，自动更新降雨数据')
			await fetchAllStationRainfallData()
			updatePolygonColors()
		} catch (error) {
			console.error('自动更新降雨数据失败:', error)
		}
	}
}, { deep: true })

// 暴露方法给父组件
defineExpose({
	fetchReservoirDetail,
	fetchThiessenData
})
</script>

<style scoped>
.reservoir-detail {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
	padding: 20rpx;
	background: #f5f7fa;
	min-height: 100vh;
}

.info-card {
	background: #ffffff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	overflow: hidden;
	border: 1rpx solid #e8eaed;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
}

.header-left {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
	flex: 1;
}

.header-right {
	display: flex;
	align-items: center;
}

.card-title {
	font-size: 36rpx;
	font-weight: 600;
}

.refresh-btn {
	background: rgba(255, 255, 255, 0.2);
	color: white;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 8rpx;
	padding: 10rpx 20rpx;
	font-size: 24rpx;
}

.recalculate-btn {
	background: rgba(255, 255, 255, 0.2);
	color: white;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 8rpx;
	padding: 12rpx 24rpx;
	font-size: 24rpx;
	/* #ifdef H5 */
	cursor: pointer;
	/* #endif */
	transition: all 0.3s ease;
}

/* #ifdef H5 */
.recalculate-btn:hover {
	background: rgba(255, 255, 255, 0.3);
}
/* #endif */

.recalculate-btn:disabled {
	opacity: 0.6;
	cursor: not-allowed;
}

.card-content {
	padding: 30rpx;
}

.info-row {
	display: flex;
	margin-bottom: 20rpx;
	align-items: flex-start;
}

.info-label {
	font-size: 28rpx;
	color: #6c757d;
	font-weight: 500;
	min-width: 160rpx;
}

.info-value {
	font-size: 28rpx;
	color: #2c3e50;
	flex: 1;
	line-height: 1.5;
}

.loading-text, .no-data-text {
	text-align: center;
	color: #6c757d;
	font-size: 28rpx;
	padding: 40rpx;
}

/* 地图布局样式 */
.map-section {
	width: 100%;
	display: flex;
	flex-direction: column;
	margin-bottom: 20rpx;
	position: relative;
}

.section-placeholder {
	text-align: center;
	color: #6c757d;
}

.placeholder-text {
	font-size: 32rpx;
	font-weight: 500;
	display: block;
	margin-bottom: 10rpx;
}

.placeholder-desc {
	font-size: 24rpx;
	opacity: 0.7;
	display: block;
}

/* 地图相关样式 */
.map-legend {
	display: flex;
	gap: 20rpx;
	flex-wrap: wrap;
}

.legend-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.legend-color {
	width: 16rpx;
	height: 16rpx;
	border-radius: 50%;
}

.legend-text {
	font-size: 24rpx;
	color: white;
}

.map-container {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
	overflow: hidden;
	background: #f5f5f5;
	position: relative;
}

/* Leaflet地图DOM元素样式 */
.leaflet-map {
	width: 100%;
	height: 100%;
	min-height: 800rpx; /* 设置最小高度确保地图可见 */
	border-radius: 12rpx;
}

/* Leaflet地图样式覆盖 */
.map-container :deep(.leaflet-container) {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
}

.map-container :deep(.leaflet-popup-content-wrapper) {
	border-radius: 8rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.map-container :deep(.leaflet-popup-content) {
	margin: 12rpx 16rpx;
	font-size: 24rpx;
	line-height: 1.4;
}

.map-container :deep(.leaflet-control-attribution) {
	font-size: 20rpx;
	background: rgba(255, 255, 255, 0.8);
}

.map-not-supported {
	text-align: center;
	padding: 100rpx 40rpx;
	color: #6c757d;
	font-size: 28rpx;
	background: #f8f9fa;
	border-radius: 12rpx;
}

/* 简易日期条样式 */
.simple-date-bar {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 12rpx;
	padding: 16rpx 20rpx;
	background: #ffffff;
	border-radius: 12rpx;
	margin: 0 20rpx 24rpx 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	border: 1rpx solid #e8eaed;
}

.date-separator {
	font-size: 26rpx;
	color: #666;
	padding: 0 8rpx;
}

/* 数据表格样式 */
.data-table {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.table-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16rpx 20rpx;
	background: #667eea;
	color: white;
	border-radius: 8rpx 8rpx 0 0;
}

.table-title {
	font-size: 28rpx;
	font-weight: 600;
}

.table-count {
	font-size: 24rpx;
	opacity: 0.9;
}

.table-container {
	flex: 1;
	border: 1rpx solid #e9ecef;
	border-top: none;
	border-radius: 0 0 8rpx 8rpx;
	overflow: hidden;
}

.data-table-content {
	width: 100%;
	height: 100%;
	max-height: 580rpx; /* 设置最大高度，超出时显示滚动条 */
	overflow-y: auto; /* 垂直滚动 */
	overflow-x: hidden; /* 隐藏水平滚动 */
}

.data-table-content table {
	width: 100%;
	border-collapse: collapse;
}

.data-table-content th,
.data-table-content td {
	padding: 16rpx;
	text-align: center;
	border-bottom: 1rpx solid #e9ecef;
	font-size: 26rpx;
}

.data-table-content th {
	background: #f8f9fa;
	font-weight: 600;
	color: #495057;
	position: sticky;
	top: 0;
}

/* 动态降雨量色带图例样式 */
.dynamic-rainfall-legend {
	position: absolute;
	bottom: 20rpx;
	right: 20rpx;
	background: rgba(255, 255, 255, 0.95);
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	padding: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	z-index: 1000;
	min-width: 120rpx;
	max-width: 200rpx;
}

.dynamic-rainfall-legend .legend-title {
	font-size: 24rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 12rpx;
	text-align: center;
}

.dynamic-rainfall-legend .legend-colors {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

/* 柱状图样式 */
.chart-container {
	width: 100%;
	height: 800rpx; /* 增加高度为滚动条留出空间 */
	position: relative;
	background: #fafbfc;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.chart-scroll-container {
	width: 100%;
	height: 100%;
	overflow-x: auto;
	overflow-y: hidden;
	border: 2rpx solid #e9ecef;
	border-radius: 8rpx;
	background: #ffffff;
	position: relative;
	/* 自定义滚动条样式 */
	scrollbar-width: thin;
	scrollbar-color: #007bff #f1f3f4;
}

/* 滚动提示 */
.chart-scroll-container::before {
	content: "← 可左右滑动查看更多数据 →";
	position: absolute;
	top: 10rpx;
	right: 20rpx;
	font-size: 24rpx;
	color: #666;
	background: rgba(255, 255, 255, 0.9);
	padding: 8rpx 16rpx;
	border-radius: 8rpx;
	z-index: 10;
	pointer-events: none;
}

/* Webkit浏览器滚动条样式 */
.chart-scroll-container::-webkit-scrollbar {
	height: 24rpx;
}

.chart-scroll-container::-webkit-scrollbar-track {
	background: #f1f3f4;
	border-radius: 12rpx;
}

.chart-scroll-container::-webkit-scrollbar-thumb {
	background: #007bff;
	border-radius: 12rpx;
	border: 4rpx solid #f1f3f4;
}

.chart-scroll-container::-webkit-scrollbar-thumb:hover {
	background: #0056b3;
}

.rainfall-chart {
	display: block;
	height: 100%;
	min-width: 4800rpx; /* 确保最小宽度 */
	/* #ifdef H5 */
	cursor: grab; /* 显示可拖拽的光标 */
	/* #endif */
}

/* #ifdef H5 */
.rainfall-chart:active {
	cursor: grabbing; /* 拖拽时的光标 */
}
/* #endif */

.chart-not-supported {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 8rpx;
	color: #666;
	font-size: 28rpx;
}

/* 降雨量图例样式 */
.rainfall-legend {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 30rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
	background: #f8f9fa;
	border-radius: 8rpx;
	border: 1rpx solid #e9ecef;
}

.rainfall-legend .legend-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.rainfall-legend .legend-color {
	width: 30rpx;
	height: 20rpx;
	border-radius: 4rpx;
	border: 1rpx solid #ddd;
}

.rainfall-legend .legend-text {
	font-size: 24rpx;
	color: #666;
	font-weight: 500;
}

/* 测站降雨量表格样式 */
.station-rainfall-table {
	width: 100%;
	border: 1rpx solid #e9ecef;
	border-radius: 8rpx;
	overflow: hidden;
}

.table-header-row {
	display: flex;
	background: #f8f9fa;
	border-bottom: 2rpx solid #e9ecef;
}

.table-header-cell {
	flex: 1;
	padding: 24rpx 20rpx;
	font-size: 28rpx;
	font-weight: 600;
	color: #495057;
	text-align: center;
	border-right: 1rpx solid #e9ecef;
}

.table-header-cell:last-child {
	border-right: none;
}

.table-header-cell.station-name {
	flex: 1;
	text-align: left;
}

.table-header-cell.rainfall-value {
	flex: 1;
}

.table-header-cell.station-address {
	flex: 1;
}

.table-row {
	display: flex;
	border-bottom: 1rpx solid #f1f3f4;
	transition: background-color 0.2s ease;
}

.table-row:hover {
	background: #f8f9fa;
}

.table-row.even-row {
	background: #fafbfc;
}

.table-row.even-row:hover {
	background: #f1f3f4;
}

.table-row.clickable-row {
	cursor: pointer;
}

.table-row.clickable-row:hover {
	background: #e3f2fd;
}

.table-row.clickable-row.even-row:hover {
	background: #e3f2fd;
}

.table-cell {
	flex: 1;
	padding: 20rpx;
	font-size: 26rpx;
	color: #333;
	text-align: center;
	border-right: 1rpx solid #f1f3f4;
}

.table-cell:last-child {
	border-right: none;
}

.table-cell.station-name {
	flex: 1;
	text-align: left;
	font-weight: 500;
}

.table-cell.rainfall-value {
	flex: 1;
	font-weight: 600;
}

.table-cell.station-address {
	flex: 1;
	font-weight: 600;
}

.empty-table {
	padding: 60rpx 20rpx;
	text-align: center;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.dynamic-rainfall-legend .legend-color-item {
	display: flex;
	align-items: center;
	gap: 2rpx;
}

.dynamic-rainfall-legend .legend-color-block {
	width: 20rpx;
	height: 20rpx;
	border-radius: 4rpx;
	border: 1rpx solid #ccc;
	flex-shrink: 0;
}

.dynamic-rainfall-legend .legend-color-label {
	font-size: 22rpx;
	color: #555;
	flex: 1;
	text-align: right;
}

.data-table-content td {
	color: #6c757d;
}

.empty-row .empty-cell {
	padding: 60rpx 20rpx;
	border: none;
}

.empty-message {
	text-align: center;
}

.empty-text {
	font-size: 28rpx;
	color: #adb5bd;
}

/* 降雨研判统计信息样式（紧凑版本） */
.rainfall-analysis {
    margin-top: 16rpx;
    margin-bottom: 16rpx;
}

.analysis-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12rpx 20rpx; /* 减少内边距 */
    background: #667eea;
    color: #ffffff;
    border-radius: 8rpx 8rpx 0 0;
}

.analysis-title {
    font-size: 28rpx; /* 稍微减小字体 */
    font-weight: 600;
}

.analysis-period {
    font-size: 22rpx; /* 稍微减小字体 */
    opacity: 0.9;
}

.analysis-stats {
    padding: 0;
    background: #ffffff;
    border: 1rpx solid #e9ecef;
    border-top: none;
    border-radius: 0 0 8rpx 8rpx;
    overflow: hidden;
}

.stats-row {
    display: flex;
    border-bottom: 1rpx solid #f0f0f0;
}

.stats-row:last-child {
    border-bottom: none;
}

.stat-cell {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16rpx 12rpx; /* 大幅减少内边距 */
    border-right: 1rpx solid #f0f0f0;
    background: #ffffff;
    position: relative;
}

.stat-cell:last-child {
    border-right: none;
}

.stat-label {
    font-size: 22rpx; /* 减小字体 */
    color: #666666;
    margin-bottom: 6rpx; /* 减少间距 */
    text-align: center;
    line-height: 1.2;
}

.stat-number {
    font-size: 32rpx; /* 大幅减小数字字体 */
    font-weight: 700;
    color: #27a9e1;
    line-height: 1;
    margin-bottom: 4rpx; /* 减少间距 */
}

.stat-number.highlight {
    color: #27a9e1;
    font-size: 36rpx; /* 相应减小高亮字体 */
}

.stat-unit {
    font-size: 20rpx; /* 减小字体 */
    color: #999999;
    text-align: center;
    line-height: 1.2;
}

/* 新的降雨研判卡片样式 */
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    border-radius: 12rpx 12rpx 0 0;
    position: relative;
    overflow: hidden;
}

.card-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="20" cy="80" r="0.5" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    pointer-events: none;
}

.card-title {
    font-size: 32rpx;
    font-weight: 600;
    position: relative;
    z-index: 1;
}

.card-header .analysis-period {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.9);
    font-weight: 500;
    position: relative;
    z-index: 1;
}

.card-content {
    padding: 30rpx 24rpx;
    background: #ffffff;
    border-radius: 0 0 12rpx 12rpx;
    border: 1rpx solid #e9ecef;
    border-top: none;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
}

.stat-item {
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
    border-radius: 12rpx;
    padding: 24rpx 16rpx;
    text-align: center;
    border: 1rpx solid rgba(102, 126, 234, 0.2);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.stat-item.clickable {
    cursor: pointer;
}

.stat-item.clickable:hover {
    transform: translateY(-4rpx);
    box-shadow: 0 12rpx 32rpx rgba(102, 126, 234, 0.3);
    border-color: rgba(102, 126, 234, 0.4);
}

.stat-item.clickable:active {
    transform: translateY(-2rpx);
    box-shadow: 0 6rpx 16rpx rgba(102, 126, 234, 0.2);
}

.stat-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.stat-item:hover::before {
    opacity: 1;
}

.stat-item:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.2);
}

.stat-item .stat-label {
    font-size: 24rpx;
    color: #666666;
    margin-bottom: 8rpx;
    display: block;
    line-height: 1.3;
    position: relative;
    z-index: 1;
}

.stat-item .stat-value {
    font-size: 28rpx;
    font-weight: 700;
    color: #667eea;
    line-height: 1.2;
    display: block;
    position: relative;
    z-index: 1;
}

.stat-item .stat-value.highlight {
    font-size: 32rpx;
    color: #764ba2;
    text-shadow: 0 2rpx 4rpx rgba(118, 75, 162, 0.2);
}
</style>